//
//  STSpaceViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/9.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "STSpaceViewController.h"

#import "STSpaceSubIntroView.h"
#import "STSpaceSubDetailInfoView.h"
#import "STSpaceSubLiteratureView.h"
#import "STSpaceSubEasyTakePicView.h"

#import "EPMainTabsView.h"

#import <TXScrollLabelView/TXScrollLabelView.h>

@interface STSpaceViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) STSpaceViewModel* viewModel;

// UI

@property (weak, nonatomic) UIButton *searchButton;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIButton* backBtn;
@property (weak, nonatomic) IBOutlet UIView* avatarBgView;
@property (weak, nonatomic) IBOutlet UIImageView* avatarImgView;
@property (weak, nonatomic) IBOutlet UILabel* nameLabel;
@property (weak, nonatomic) IBOutlet UILabel* userTypeLabel;
@property (weak, nonatomic) IBOutlet UIView* tagView;
@property (weak, nonatomic) IBOutlet UIButton* focusBtn;
@property (weak, nonatomic) IBOutlet UIView* tabsView;
@property (weak, nonatomic) IBOutlet UIView* scrollTextView;
@property (weak, nonatomic) IBOutlet UIScrollView* tabContentScrollView;

@end

@implementation STSpaceViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    NSLog(@"viewDidLayoutSubviews");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* willDisAppearSignal = [[self rac_signalForSelector:@selector(viewWillDisappear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }];
    
    [willDisAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        NSLog(@"viewDidAppear");
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        [self.viewModel.reqDataCmd execute:nil];
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    RACSignal* loadOverSignal = [self.viewModel.reqDataCmd.executionSignals.switchToLatest filter:^BOOL(id value)
    {
        BOOL isLoadFinish = [value boolValue];
        
        return isLoadFinish;
    }];
    
    [[[willAppearSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
    {
        [MBProgressHUD mh_showProgressHUD:@""];
    }];
    
    [[[[[viewDidLayoutSVSignal take:1] zipWith:didAppearSignal] zipWith:loadOverSignal] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         [MBProgressHUD mh_hideHUD];
         
         //重置 更新 frame
         [self _setupAllView];
     }];

#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RAC(self.userTypeLabel, text) = RACObserve(self.viewModel, userType);
    
    [[_backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
    {
        @strongify(self);
        [self _back];
    }];
}

#pragma mark - 更新初始化 操作
- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    // 宣言滚动Label
    // step1:获取滚动内容
    NSString *scrollTitle = self.viewModel.userDetailData.user.declaration;
    // step2:创建scrollLabelView对象
    TXScrollLabelView *scrollLabelView = [TXScrollLabelView scrollWithTitle:scrollTitle type:TXScrollLabelViewTypeLeftRight velocity:3 options:UIViewAnimationOptionTransitionNone];
    scrollLabelView.backgroundColor = [UIColor clearColor];
    scrollLabelView.scrollTitleColor = [UIColor blackColor];
    // step3:设置代理进行回调（Optional）
    //    scrollLabelView.scrollLabelViewDelegate = self;
    // step4:布局
    scrollLabelView.frame = (CGRect) {0, 0, self.scrollTextView.frame.size};
    [self.scrollTextView addSubview:scrollLabelView];
    //    [scrollLabelView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(speakerImage.mas_top);
    //        make.left.equalTo(speakerImage.mas_right).with.offset(0);
    //        make.size.mas_equalTo(CGSizeMake(240, 21));
    //    }];
    // step5:开始滚动
    [scrollLabelView beginScrolling];
    
    self.nameLabel.text = self.viewModel.userDetailData.user.nickname;
    
    self.avatarBgView.layer.cornerRadius = self.avatarBgView.frame.size.height/2.0f;
    self.avatarBgView.layer.masksToBounds = YES;
    
    [self.avatarImgView yy_setImageWithURL:[NSURL URLWithString:self.viewModel.userDetailData.user.headimg] placeholder:MHImageNamed(@"placeholderLogo")];
    self.avatarImgView.layer.cornerRadius = self.avatarImgView.frame.size.height/2.0f;
    self.avatarImgView.layer.masksToBounds = YES;
    
    self.tagView.layer.cornerRadius = self.tagView.frame.size.height/2.0f;
    self.tagView.layer.masksToBounds = YES;
    
    [self _setupTabsView];
    
    [self _setupContentScrollView];
}

- (void)_setupTabsView
{
    @weakify(self);
    
    CGSize tabContentScrollViewSize = self.tabContentScrollView.frame.size;
    
    EPMainTabsViewModel* vm = [[EPMainTabsViewModel alloc] init];
    vm.tabInfos = self.viewModel.tabInfos;
    [vm.didClickTab subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSLog(@"TabsView select index : %d", [x integerValue]);
         
         NSInteger index = [x integerValue];
         
         [self.tabContentScrollView scrollRectToVisible:(CGRect) {index*tabContentScrollViewSize.width, 0, tabContentScrollViewSize} animated:YES];
     }];
    
    EPMainTabsView* curView = [[EPMainTabsView alloc] initWithFrame:(CGRect) {0, 0, self.tabsView.frame.size}];
    [curView bindViewModel:vm];
    curView.tag = 99;
    [self.tabsView addSubview:curView];
}

- (void)_setupContentScrollView
{
    @weakify(self);
    
    NSInteger tabCount = self.viewModel.tabInfos.count;
    
    CGFloat scrollViewWidth = [UIScreen mainScreen].bounds.size.width * tabCount;
    NSLog(@"scrollViewWidth 1 : %f", scrollViewWidth);
    
    UIView* tabContentView = [self.tabContentScrollView viewWithTag:100];
    
    //    tabContentView.backgroundColor = [UIColor yellowColor];
    
    //    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MainSubMainView" owner:nil options:nil];
    //    UIView* mainView = [views lastObject];
    //    mainView.frame = (CGRect) {0, 0, self.view.frame.size};
    //    [tabContentView addSubview:mainView];
    
    
    for (NSLayoutConstraint* curConstraint in tabContentView.constraints)
    {
        if (curConstraint.firstAttribute == NSLayoutAttributeWidth)
        {
            curConstraint.constant = scrollViewWidth;
            break;
        }
    }
    [tabContentView setNeedsUpdateConstraints];
    [tabContentView updateConstraintsIfNeeded];
    [tabContentView setNeedsLayout];
    [tabContentView layoutIfNeeded];
    
    for (NSInteger index=0; index<tabCount; index++)
    {
        NSDictionary* tabInfo = self.viewModel.tabInfos[index];
        
        NSString* curTabName = tabInfo[@"TabName"];
        
        if ([curTabName containsString:@"简介"])
        {
            STSpaceSubIntroViewModel* vm = [[STSpaceSubIntroViewModel alloc] initWithParams:@{}];
            vm.intro = self.viewModel.expertData.expertInfo.summary;
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"STSpaceSubIntroView" owner:nil options:nil];
            STSpaceSubIntroView* view = [views lastObject];
            view.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*index, 0, self.tabContentScrollView.bounds.size};
            [view bindViewModel:vm];
            view.tag = 1;
            [tabContentView addSubview:view];
        }
        else if ([curTabName containsString:@"详情"])
        {
            STSpaceSubDetailInfoViewModel* vm = [[STSpaceSubDetailInfoViewModel alloc] initWithParams:@{}];
            vm.contactContent = HCStrFormat(@"联系人：%@\n联系电话：%@\n联系地址：%@\n", self.viewModel.institutionData.institutionInfo.name, self.viewModel.institutionData.institutionInfo.mobile, self.viewModel.institutionData.institutionInfo.address);
            vm.servContent = self.viewModel.institutionData.institutionInfo.service;
            vm.introContent = self.viewModel.institutionData.institutionInfo.summary;
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"STSpaceSubDetailInfoView" owner:nil options:nil];
            STSpaceSubDetailInfoView* view = [views lastObject];
            view.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*index, 0, self.tabContentScrollView.bounds.size};
            [view bindViewModel:vm];
            view.tag = 2;
            [tabContentView addSubview:view];
        }
        else if ([curTabName containsString:@"生态文献"])
        {
            STSpaceSubLiteratureViewModel* vm = [[STSpaceSubLiteratureViewModel alloc] initWithParams:@{}];
            vm.stwxTVM.userID = self.viewModel.userID;
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"STSpaceSubLiteratureView" owner:nil options:nil];
            STSpaceSubLiteratureView* view = [views lastObject];
            view.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*index, 0, self.tabContentScrollView.bounds.size};
            [view bindViewModel:vm];
            view.tag = 3;
            [tabContentView addSubview:view];
        }
        else if ([curTabName containsString:@"生态行动"])
        {
            STSpaceSubEasyTakePicViewModel* vm = [[STSpaceSubEasyTakePicViewModel alloc] initWithParams:@{}];
            vm.myEasyTakePicTVM.reqUserID = self.viewModel.userID;
            NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"STSpaceSubEasyTakePicView" owner:nil options:nil];
            STSpaceSubEasyTakePicView* view = [views lastObject];
            view.frame = (CGRect) {self.tabContentScrollView.bounds.size.width*index, 0, self.tabContentScrollView.bounds.size};
            [view bindViewModel:vm];
            view.tag = 4;
            [tabContentView addSubview:view];
        }
        else if ([curTabName containsString:@"生态树"])
        {
            UIView* view = [[UIView alloc] initWithFrame:(CGRect) {self.tabContentScrollView.bounds.size.width*index, 0, self.tabContentScrollView.bounds.size}];
            view.backgroundColor = [UIColor clearColor];
            view.tag = 5;
            [tabContentView addSubview:view];
            
            UILabel* label = [[UILabel alloc] initWithFrame:(CGRect) {0, view.frame.size.height/2.0f - 12.0f, view.frame.size.width, 24.0f}];
            label.text = @"该项功能暂未开通";
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:16.0f];
            [view addSubview:label];
        }
    }
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_back
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
